<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <h2>创建新账号</h2>
          <p>注册成为我们的新会员</p>
        </div>
      </template>

      <!-- 注册表单 -->
      <el-form
          ref="registerForm"
          :model="form"
          :rules="formRules"
          label-position="top"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="4-20个字符"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="mobile">
          <el-input
              v-model="form.mobile"
              placeholder="请输入手机号"
              prefix-icon="Iphone"
              clearable
              maxlength="11"
          />
          <div :class="['tip', { 'valid': mobileValid }]" v-if="mobileTip">
            <el-icon :color="mobileValid ? 'success' : 'error'">
              <SuccessFilled v-if="mobileValid" />
              <WarningFilled v-else />
            </el-icon>
            {{ mobileTip }}
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="6-20位密码"
              prefix-icon="Lock"
              show-password
              @input="updatePasswordStrength"
          />
        </el-form-item>

        <!-- 安全度提示 - 移到确认密码输入框上方 -->
        <div v-if="form.password.length > 0" class="strength-tip">
          <span class="strength-text">
            安全度: <span :class="strengthClass">{{ strengthText }}</span>
          </span>
        </div>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <!-- 用户协议 -->
        <el-form-item prop="agreeToPolicy">
          <el-checkbox v-model="form.agreeToPolicy">
            我已阅读并同意
            <el-link type="primary" @click="showPolicy">《用户协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loading"
              @click="submitRegister"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 已有账号？ -->
      <div class="login-footer">
        <span>已有账号？</span>
        <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>
    </el-card>
  </div>

  <!-- 协议弹窗 -->
  <el-dialog v-model="policyVisible" title="用户协议" width="70%">
    <div v-html="policyContent"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="policyVisible = false">同意</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="privacyVisible" title="隐私政策" width="70%">
    <div v-html="privacyContent"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="privacyVisible = false">同意</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import {
  ElMessage,
  ElMessageBox,
  ElNotification
} from 'element-plus';
import {
  WarningFilled,
  SuccessFilled
} from '@element-plus/icons-vue';
import axios from 'axios';

// 使用路由对象
const router = useRouter();

// 注册表单数据
const form = ref({
  username: '',
  mobile: '',
  password: '',
  confirmPassword: '',
  agreeToPolicy: false
});

// 注册表单引用
const registerForm = ref(null);

// 加载状态
const loading = ref(false);

// 验证相关状态
const mobileTip = ref('');
const passwordStrength = ref(0);
const policyVisible = ref(false);
const privacyVisible = ref(false);
const mobileValid = ref(false);

// 协议内容
const policyContent = `
  <h2>用户协议</h2>
  <p>1. 用户在使用本服务前需要注册一个账号。</p>
  <p>2. 用户需提供真实、准确、完整的个人信息，并保证即时更新。</p>
  <p>3. 用户应妥善保管账号及密码的安全，不得转让或出借给他人使用。</p>
  <p>4. 用户不得发布或传播违反国家法律法规的信息内容。</p>
  <p>5. 用户同意本平台依法保护个人信息安全和隐私。</p>
`;

const privacyContent = `
  <h2>隐私政策</h2>
  <p>1. 我们收集的个人信息类型包括但不限于手机号、用户名、密码等。</p>
  <p>2. 收集信息用于注册账户、身份验证、服务提供和客户支持。</p>
  <p>3. 我们采用行业标准安全措施保护您的个人信息。</p>
  <p>4. 未经您同意，我们不会向第三方分享您的个人信息。</p>
  <p>5. 您有权访问、更正或删除您的个人信息。</p>
`;

// 表单验证规则
const formRules = ref({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度4-20个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请填写正确的手机号'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 5, message: '密码长度至少为5位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  agreeToPolicy: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

// 监听手机号变化
watch(() => form.value.mobile, (newVal) => {
  if (!newVal) {
    mobileTip.value = '';
    return;
  }

  if (newVal.length < 11) {
    mobileTip.value = `还需${11 - newVal.length}位数字`;
    mobileValid.value = false;
  } else if (!/^1[3-9]\d{9}$/.test(newVal)) {
    mobileTip.value = '手机号格式不正确';
    mobileValid.value = false;
  } else {
    mobileTip.value = '手机号格式正确';
    mobileValid.value = true;
  }
});

// 监听密码变化
watch(() => form.value.password, (newVal) => {
  validatePassword(newVal);
});

// 密码强度验证方法
const validatePassword = (password) => {
  let strength = 0;

  if (password.length >= 5) strength++;
  if (password.length >= 8) strength++;
  if (/[A-Z]/.test(password)) strength++;
  if (/[0-9]/.test(password)) strength++;
  if (/[^A-Za-z0-9]/.test(password)) strength++;

  passwordStrength.value = strength;
};

// 密码强度状态文字
const strengthText = computed(() => {
  const texts = ['低', '中', '较高', '高', '非常高'];
  return texts[passwordStrength.value - 1] || '低';
});

// 密码强度分类
const strengthClass = computed(() => {
  if (passwordStrength.value <= 1) return 'weak';
  if (passwordStrength.value <= 3) return 'medium';
  return 'strong';
});

// 更新密码强度（用于即时响应）
const updatePasswordStrength = () => {
  validatePassword(form.value.password);
};

// 显示用户协议
const showPolicy = () => {
  policyVisible.value = true;
};

// 显示隐私政策
const showPrivacy = () => {
  privacyVisible.value = true;
};

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};

// 提交注册表单
const submitRegister = async () => {
  // 表单验证
  try {
    await registerForm.value.validate();
  } catch (error) {
    return;
  }

  // 检查手机号
  if (!mobileValid.value) {
    ElMessage.error('请填写正确的手机号');
    return;
  }

  // 检查密码强度
  if (passwordStrength.value < 2) {
    ElMessage.warning('您的密码强度较弱，建议增加长度或使用数字、特殊字符');
    return;
  }

  loading.value = true;

  try {
    const data = {
      username: form.value.username,
      mobile: form.value.mobile,
      password: form.value.password
    };

    const response = await axios.post('/api/user/register', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 处理响应
    if (response.data?.success || response.status === 200) {
      ElNotification({
        title: '注册成功',
        message: `欢迎 ${form.value.username}，请登录您的账号`,
        type: 'success',
        duration: 3000
      });

      // 重置表单
      registerForm.value.resetFields();

      // 延迟跳转到登录页
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    } else {
      const errorMsg = response.data?.message || '注册失败，请重试';
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error('注册请求错误:', error);

    // 更友好的错误提示
    if (error.response?.status === 409) {
      ElMessage.error('该手机号已注册，请直接登录');
    } else if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('服务器响应异常，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 450px;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);

  .login-header {
    text-align: center;
    padding: 10px 0;
    h2 {
      color: #2c3e50;
      font-weight: 600;
      margin: 0;
      font-size: 24px;
    }

    p {
      color: #7f8c8d;
      margin-top: 8px;
      font-size: 14px;
    }
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #34495e;
  padding-bottom: 5px;
  font-size: 14px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
  font-size: 16px;
  letter-spacing: 2px;
  height: 46px;
}

.login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
  color: #7f8c8d;
  font-size: 14px;

  .el-link {
    margin-left: 8px;
    font-size: 14px;
  }
}

.tip {
  font-size: 12px;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c; /* 默认红色（用于错误提示） */
}

.tip.valid {
  color: #67c23a; /* 有效时改为绿色（与ElementUI成功色一致） */
}

/* 安全度提示 - 放在确认密码输入框上方 */
.strength-tip {
  margin: 8px 0 10px;
  font-size: 12px;

  .strength-text {
    color: #909399;

    span {
      font-weight: 500;
      &.weak {
        color: #f56c6c;
      }
      &.medium {
        color: #e6a23c;
      }
      &.strong {
        color: #67c23a;
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 15px;

    .login-header h2 {
      font-size: 22px;
    }
  }
}
</style>